package com.huluobo.lc.kotlinim1812a.contract.contract

import android.util.Log
import com.huluobo.lc.kotlinim1812a.data.ContactListItem
import com.huluobo.lc.kotlinim1812a.db.Contact
import com.huluobo.lc.kotlinim1812a.db.IMDatabase
import com.hyphenate.chat.EMClient
import com.hyphenate.exceptions.HyphenateException
import org.jetbrains.anko.doAsync

/**
 * @author Lc
 * @description:
 * @date :2021/6/23 16:19
 */
class ContactPresenter(val view: ContactContact.View) : ContactContact.Presenter {
    val contactListItems = mutableListOf<ContactListItem>()

    override fun loadContacts() {
        doAsync {
            try {
                contactListItems.clear()
                IMDatabase.instance.deleteAllContacts()
                val userNames = EMClient.getInstance().contactManager().allContactsFromServer
                //按照首字母进行排序
                userNames.sortBy { it[0] }

//                userNames.forEach {
//                    //拿到每一个联系人对象(名字,首字符)
//                    //it 代表userNames中的每个String,toUpperCase 转换为答谢
//                    val contactListItem = ContactListItem(it, it[0].toUpperCase())
//                    contactListItems.add(contactListItem)
//                }

                userNames.forEachIndexed { index, it ->
                    //什么时候显示首字符,当index=0
                    //username上一位的首字符如果和当前首字符不同
                    val showFirstLetter = index == 0 || it[0] != userNames[index - 1][0]
                    val contactListItem = ContactListItem(it, it[0].toUpperCase(), showFirstLetter)
                    contactListItems.add(contactListItem)

                    val contact = Contact(mutableMapOf("name" to it))
                    IMDatabase.instance.saveContact(contact)
                }

                runOnUIThread { view.onLoadContactsSuccess() }
            } catch (e: HyphenateException) {
                runOnUIThread { view.onLoadContactsFailed() }
            }
        }
    }
}